<template>
  <ul>
    <li v-for="item in plist" :key="item.id">
      <img :src="baseimgurl + item.path" alt="加载失败" />
      <i class="iconfont icon-closel" @click="deleteOnePhoto(item.id)"></i>
    </li>
  </ul>
  <input type="file" @change="addOnePhoto" />
  <el-button @click="deleteEveryPhotos">删除所有的图片</el-button>
</template>

<script setup lang="ts">
import { closeSync } from 'fs'
import { onMounted, ref } from 'vue'
import '../assets/css/icon/cykicon/iconfont.css'
import {
  deletePhotoById,
  postPhotoById,
  deleteAllPhoto
} from '../services/items'
const props = defineProps<{
  a: { id: string; path: string; order: number }[]
  Itemid: string
}>()
const { a } = props
const plist = ref<{ id: string; path: string; order: number }[]>([])
onMounted(() => {
  plist.value = a
})
const baseimgurl = 'http://159.75.101.15:3000/'
/**
 * 删除一张图片
 * @param pid
 */
async function deleteOnePhoto(pid: string) {
  try {
    await deletePhotoById(props.Itemid, pid)
    const result: { id: string; path: string; order: number }[] = []
    props.a.forEach((obj) => {
      if (obj.id != pid) {
        result.push(obj)
      }
    })
    plist.value = result
  } catch (error) {}
}
/**
 *
 * @param e 上传图片
 */
async function addOnePhoto(e: Event) {
  // const newarray = []
  if (plist.value.length >= 3) {
    alert('最多添加3张图片!!')
  } else {
    const target = e.target as HTMLInputElement
    const file: File = (target.files as FileList)[0]
    console.log(file)
    const formdata = new FormData()
    formdata.append('files', file)
    // newarray.push(formdata)
    plist.value = (await postPhotoById(props.Itemid, formdata)).data
  }
}
/**
 *
 */
async function deleteEveryPhotos() {
  try {
    await deleteAllPhoto(props.Itemid)
    plist.value = []
  } catch (error) {}
}
</script>

<style lang="less" scoped>
ul {
  list-style-type: none;
  li {
    display: inline-block;
    position: relative;
    img {
      margin-left: 20px;
      width: 85px;
      height: 85px;
    }
    i {
      position: absolute;
      right: -1px;
      top: -1px;
    }
  }
}
</style>

